package cc.opcol.iot.server.util;

import org.apache.commons.lang.StringUtils;

public class HexUtil {
    static HexUtil hexUtil=new HexUtil();
    public static HexUtil getInstance(){
        return hexUtil;
    }

    public  byte[] hexStringToBye(String[] hexString){
        byte out[]=new byte[hexString.length];
        for(int i=0;i<hexString.length;i++){
            out[i]=Integer.valueOf(hexString[i],16).byteValue();
        }
        return  out;
    }

    public  String reverse(String s,int stepLen) {
        StringBuffer stringBuffer=new StringBuffer();
        String[] spiltSeg= split(s, stepLen);
        for (int j=spiltSeg.length-1;j>=0;j-- ){
            stringBuffer.append(spiltSeg[j]);
        }
        s=stringBuffer.toString();
        return s;
    }

    public  String[] split(String msg, int spitStep) {
        if(spitStep==0){
            return null;
        }
        StringBuffer stringBuffer = new StringBuffer();
        int step=0;
        for(int i=0;i<msg.length();i++){
            stringBuffer.append(msg.charAt(i));
            step++;
            if(step==spitStep){
                step=0;
                stringBuffer.append(",");
            }
        }
        return StringUtils.split(stringBuffer.toString(),",");
    }

    public  String byteToHexString(byte num) {
        String hexStr=Integer.toHexString(num & 0xFF);
        if(hexStr.length()<2){
            hexStr="0"+hexStr;
        }
        return hexStr.toUpperCase();
    }

    public String bytesToHex(byte[] c, int len) {
        StringBuffer stringBuffer=new StringBuffer();
        for(int i=0;i<len;i++){
            stringBuffer.append(byteToHexString(c[i]));
        }
        return stringBuffer.toString();
    }

    public String hexToString(String cmd){
        return new String(hexStringToBye(split(cmd,2)));
    }

    public byte[] hexStringToByes(String hex) {
        String[] s=split(hex,2);
        return hexStringToBye(s);
    }
}
